<template>
  <div id="activity-list">
    <div style="margin-bottom: 20px;">
      <el-input v-model="searchKeyword" placeholder="请输入关键词"></el-input>
      <el-button size="mini" type="primary" @click="searchActivities">搜索</el-button>
    </div>
    <div class="activity-block" v-for="(activity, index) in filteredActivities" :key="index" @click="viewActivity(index)">
      <h2>{{ activity.id }}</h2>
      <h2>{{ activity.name }}</h2>
      <p>{{ activity.description }}</p>
    </div>
    <div style="position: absolute; top: 10px; right: 10px;">
      <el-button size="mini" type="primary" @click="register">注册</el-button>
      <el-button size="mini" type="primary" @click="login">登录</el-button>
    </div>
  </div>
</template>

<script>
import { fetchActivities } from '../api/api';
export default {
  name: 'Home',
  data() {
    return {
      activities: [],
      searchKeyword: '',
      filteredActivities: [],
    };
  },
  mounted() {
    this.fetchActivities(); 
  },

  methods: {
    fetchActivities() {
      fetchActivities()
        .then(response => {
          this.activities = response.data;
          this.searchActivities();
        })
        .catch(error => {
          console.log(error);
        });
    },
    getImageUrl(imageUrl) {
      return `${imageUrl}`;
    },
    viewActivity(index) {
      const activityId = this.filteredActivities[index].id;
      this.$router.push({ name: 'activitydetail', params: { id: activityId } });
    },
    register() {
      this.$router.push({ name: 'register' });
    },
    login() {
      this.$router.push({ name: 'Login' });
    },
    searchActivities() {
      if (this.searchKeyword.trim() === '') {
      this.filteredActivities = this.activities;
        } else {
          this.filteredActivities = this.activities.filter(activity => {
            return (
            activity.name.includes(this.searchKeyword.trim()) ||
            activity.description.includes(this.searchKeyword.trim())
          );
       }
      );
      if (this.filteredActivities.length === 0) {
      alert("没有找到匹配的活动");
        }
      }
    },
  },
};
</script>

<style scoped>
#activity-list {
  width: 80%;
  margin: 0 auto;
  font-family: Arial, sans-serif;
}

h1 {
  text-align: center;
  color: #333;
}

.el-input {
  width: 200px;
}

.activity-block {
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
  background-color: #f9f9f9;
}

.activity-block h2 {
  margin: 0;
  color: #333;
}

.activity-block p {
  margin: 5px 0;
  color: #666;
}

.el-button {
  margin-left: 10px;
}
</style>

